package com.crb.smartcarddemo;

import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.crb.smartcard.SmartCardService;
import com.crb.smartcard.core.OperationCallBack;

import com.crb.smartcard.core.bean.CApdu;
import com.crb.smartcard.core.bean.GetSimCardIdResult;
import com.crb.smartcard.core.bean.InitResult;
import com.crb.smartcard.core.bean.OpenChannelResult;

import com.crb.smartcard.core.bean.RApdu;
import com.crb.smartcard.core.oma.ReaderType;
//import com.crb.smartcard.utils.LogUtil;

import com.crb.smartcarddemo.http.Bean.CardData;
import com.crb.smartcarddemo.http.HttpUtils;
import com.crb.smartcarddemo.http.RequestBean.ApplyReq;
import com.crb.smartcarddemo.http.RequestBean.ResultReq;
import com.crb.smartcarddemo.http.RequestBean.SynReq;
import com.crb.smartcarddemo.http.ResponseBean.ApplyResp;
import com.crb.smartcarddemo.http.ResponseBean.ResultResp;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private Context context;

    private Button initSdk;
    private Button openChannel;
    private Button transmitApdu;
    private Button closeChannel;
    private Button getSimCardId;
    private Button toPersonal;
    private Button toSyn;
    private String taskId;
    private String seid;
    private ProgressDialog progressDialog;
    private boolean init_Sdk = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        setContentView(R.layout.activity_main);

        initSdk = findViewById(R.id.initSdk);
        openChannel = findViewById(R.id.openChannel);
        transmitApdu = findViewById(R.id.transmitApdu);
        closeChannel = findViewById(R.id.closeChannel);
        getSimCardId = findViewById(R.id.getSimCardId);
        toPersonal = findViewById(R.id.toPersonal);
        toSyn = findViewById(R.id.toSyn);


        progressDialog = new ProgressDialog(context);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setIndeterminate(true);
        progressDialog.setMessage("个人化进行中，请稍等...");


        testSdk();
    }

    private void testSdk() {
        //初始化SDK
        initSdk.setOnClickListener(v -> {
            SmartCardService.initialize(ReaderType.TYPE_SIM, new OperationCallBack<InitResult>() {
                @Override
                public void execute(InitResult initResult) {
                    Log.i(TAG, "initialize:" + initResult.toString());
                    if(initResult.isResult()){
                        init_Sdk = true;
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(context, "初始化：" + initResult.toString(),
                                    Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            });
        });

        //打开通道
        openChannel.setOnClickListener(v -> {
//            SmartCardService.openChannel("00A4040010F0000000000390038F00000100000081", new OperationCallBack<OpenChannelResult>() {
//            SmartCardService.openChannel("00A4040007A0000001510000", new OperationCallBack<OpenChannelResult>() {
            SmartCardService.openChannel("00A4040010D1560001350302100000010000080000", new OperationCallBack<OpenChannelResult>() {
                @Override
                public void execute(OpenChannelResult openChannelResult) {
                    Log.i(TAG, "openChannel:" + openChannelResult.toString());
                }
            });
        });

        //指令传输
        transmitApdu.setOnClickListener(v -> {
            List<CApdu> cApduList = new ArrayList<>();
//            cApduList.add(new CApdu("1", "00A404000F0378312E73682EC9E7BBE1B1A3D5CF", "9000|6283"));
            cApduList.add(new CApdu("1", "00a4000c022fe2", "9000|6283"));
            cApduList.add(new CApdu("1", "00b000000A", "9000|6283"));
//            cApduList.add(new CApdu("1", "00A4040010F0000000000390038F00000100000081", "9000"));
            SmartCardService.transmitApdu(cApduList, new OperationCallBack<List<RApdu>>() {
                @Override
                public void execute(List<RApdu> rApdus) {
                    Log.i(TAG, "transmitApdu:" + rApdus.toString());
                }
            });
        });

        //关闭通道
        closeChannel.setOnClickListener(v -> {
            SmartCardService.closeChannel();
        });

        //获取卡号
        getSimCardId.setOnClickListener(v -> {
            if(!init_Sdk){
                Toast.makeText(context, "获取卡号：" + "请先初始化SDK！",
                        Toast.LENGTH_SHORT).show();
                return;
            }
            SmartCardService.getSimCardId(new OperationCallBack<GetSimCardIdResult>() {
                @Override
                public void execute(GetSimCardIdResult s) {
                    Log.i(TAG, "getSimCardId:" + s);
                    seid = s.getCardId();

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(context, "获取卡号：" + s.toString(),
                                    Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            });
        });

        //个人化
        toPersonal.setOnClickListener(v -> {
            if(!init_Sdk){
                Toast.makeText(context, "获取卡号：" + "请先初始化SDK！",
                        Toast.LENGTH_SHORT).show();
                return;
            }

            if (TextUtils.isEmpty(seid)) {
                Toast.makeText(context, "个人化请求异常:" + "请先获取卡号",
                        Toast.LENGTH_SHORT).show();
                return;
            }
            progressDialog.show();
            CardData cardData = new CardData();
            cardData.setCardType("1");
            cardData.setSpecVersion("1");
            cardData.setInitInsoCde("1");
            cardData.setIssueDate("20231010");
            cardData.setValidDate("20241010");
            cardData.setCardNo("20231010010090910112");
            cardData.setUserName("闫双斌");
            cardData.setsInsCode("130824199209090766");
            cardData.setMaleCode("男");
            cardData.setNationCode("H");
            cardData.setBornDate("");
            cardData.setBirthPalce("");
            cardData.setCardIdentificationCode("222876000");
            ApplyReq applyReq = new ApplyReq();
            applyReq.setMsisdn("15201380543");
            applyReq.setSeId(seid);
            applyReq.setSeType(1);
            applyReq.setOperType(3);
            applyReq.setPersonalData(cardData);
            applyReq.setAts("WWWW");

            HttpUtils.getInstance().apply(applyReq, new Callback<ApplyResp>() {
                @Override
                public void onResponse(Call<ApplyResp> call, Response<ApplyResp> response) {
                    if (response.body().getResultCode().equals("0000")) {
                        taskId = response.body().getTaskId();
                        List<CApdu> capdus = response.body().getCapdus();
                        transmitApdu(capdus);
                    } else {
                        progressDialog.dismiss();
                        Toast.makeText(context, "个人化请求异常：" + response.body().getResultCode() + "，" + response.body().getResultDesc(),
                                Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<ApplyResp> call, Throwable t) {
                    Toast.makeText(context, "个人化请求异常" + t.getMessage(),
                            Toast.LENGTH_SHORT).show();
                }
            });
        });

        toSyn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SynReq synReq = new SynReq();
                synReq.setSeId(seid);
                synReq.setStatus(1);
                HttpUtils.getInstance().syn(synReq, new Callback<com.crb.smartcarddemo.http.ResponseBean.Response>() {
                    @Override
                    public void onResponse(Call<com.crb.smartcarddemo.http.ResponseBean.Response> call, Response<com.crb.smartcarddemo.http.ResponseBean.Response> response) {

                    }

                    @Override
                    public void onFailure(Call<com.crb.smartcarddemo.http.ResponseBean.Response> call, Throwable t) {

                    }
                });
            }
        });
    }

    //指令执行
    private void transmitApdu(List<CApdu> cApduList) {
        Log.i(TAG, "transmitApdu11111:" + cApduList.toString());
        SmartCardService.transmitApdu(cApduList, new OperationCallBack<List<RApdu>>() {
            @Override
            public void execute(List<RApdu> rApdus) {
                Log.i(TAG, "transmitApdu:" + rApdus.toString());
                toResult(rApdus);
            }
        });
    }

    //执行结果通知
    private void toResult(List<RApdu> rApdus) {
        ResultReq resultReq = new ResultReq();
        resultReq.setTaskId(taskId);
        resultReq.setRapdus(rApdus);
        HttpUtils.getInstance().result(resultReq, new Callback<ResultResp>() {
            @Override
            public void onResponse(Call<ResultResp> call, Response<ResultResp> response) {
                if (response.body().getResultCode().equals("0000")) {
                    taskId = response.body().getTaskId();
                    List<CApdu> capdus = response.body().getCapdus();
                 /*   if (capdus.size() == 0 || capdus == null) {
                        Toast.makeText(context, "个人化完成",
                                Toast.LENGTH_LONG).show();
                        progressDialog.dismiss();
                        return;
                    }*/

                    if (capdus != null ) {
                        transmitApdu(capdus);
                        progressDialog.dismiss();
                    } else {
                        progressDialog.dismiss();
                        Toast.makeText(context, "个人化完成",
                                Toast.LENGTH_LONG).show();
                    }
                } else {
                    progressDialog.dismiss();
                    Toast.makeText(context, "执行结果请求异常：" + response.body().getResultCode() + "，" + response.body().getResultDesc(),
                            Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ResultResp> call, Throwable t) {
                progressDialog.dismiss();
                Toast.makeText(context, "执行结果请求异常" + t.getMessage(),
                        Toast.LENGTH_SHORT).show();
            }
        });
    }


}